<template>
  <div class="customer-container">
    <el-card>
      <div class="search-bar">
        <el-input
            v-model="keyword"
            placeholder="请输入关键词搜索"
            style="width: 300px"
            clearable
        >
          <template #append>
            <el-button @click="handleSearch" icon="Search" />
          </template>
        </el-input>
        <el-button type="primary" @click="showAddDialog">新增客户</el-button>
      </div>

      <el-table
          :data="customerList"
          border
          style="width: 100%; margin-top: 15px"
          v-loading="loading"
      >
        <el-table-column prop="customerId" label="客户ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="name" label="客户名称" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button
                size="small"
                @click="handleEdit(scope.row)"
                icon="Edit"
            >
              编辑
            </el-button>
            <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.row.customerId)"
                icon="Delete"
                :disabled="scope.row.status === 0"
            >
              删除
            </el-button>
            <el-button
                size="small"
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                @click="handleStatusChange(scope.row)"
                icon="RefreshRight"
            >
              {{ scope.row.status === 1 ? "停用" : "启用" }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑客户对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="500px"
    >
      <el-form
          :model="form"
          ref="formRef"
          :rules="rules"
          label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAdd">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {ref, reactive, onMounted} from "vue";
import {ElMessage} from "element-plus";
// 导入封装的 API
import {
  getCustomerList,
  searchCustomers,
  addCustomer,
  updateCustomer,
  deleteCustomer,
  disableCustomer,
  enableCustomer,
  getCustomerById,
} from "../api/customer";

export default {
  name: "Customer",
  setup() {
    // 数据
    const customerList = ref([]);
    const keyword = ref("");
    const loading = ref(false);
    const dialogVisible = ref(false);
    const dialogTitle = ref("");
    const isAdd = ref(true);
    const formRef = ref(null);

    // 表单数据
    const form = reactive({
      customerId: null,
      username: "",
      password: "",
      name: "",
      contact: "",
      phone: "",
      email: "",
      status: 1,
    });

    // 表单验证规则
    const rules = {
      username: [
        {required: true, message: "请输入用户名", trigger: "blur"},
        {min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur"},
      ],
      password: [
        {required: true, message: "请输入密码", trigger: "blur"},
        {min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur"},
      ],
      name: [
        {required: true, message: "请输入客户名称", trigger: "blur"},
      ],
      phone: [
        {required: true, message: "请输入电话", trigger: "blur"},
      ],
    };

    // 获取客户列表
    const loadCustomerList = async () => {
      loading.value = true;
      try {
        const res = await getCustomerList();
        // console.log(res)
        customerList.value = res.data;
      } catch (error) {
        console.error(error);
      } finally {
        loading.value = false;
      }
    };

    // 搜索客户
    const handleSearch = async () => {
      if (!keyword.value) {
        await loadCustomerList();
        return;
      }

      loading.value = true;
      try {
        const res = await searchCustomers(keyword.value);
        customerList.value = res.data;
      } catch (error) {
        console.error(error);
      } finally {
        loading.value = false;
      }
    };

    // 显示添加对话框
    const showAddDialog = () => {
      isAdd.value = true;
      dialogTitle.value = "新增客户";
      // 重置表单
      Object.keys(form).forEach((key) => {
        form[key] = key === "status" ? 1 : "";
      });
      dialogVisible.value = true;
    };

    // 编辑客户
    const handleEdit = async (row) => {
      isAdd.value = false;
      dialogTitle.value = "编辑客户";
      try {
        const {data:data} = await getCustomerById(row.customerId);
        const customer = data.data;
        // 复制数据到表单
        Object.keys(form).forEach((key) => {
          form[key] = customer[key];
        });
        dialogVisible.value = true;
      } catch (error) {
        ElMessage.error("获取客户详情失败");
        console.error(error);
      }
    };

    // 提交表单
    const submitForm = async () => {
      await formRef.value.validate();

      try {
        if (isAdd.value) {
          await addCustomer(form);
          ElMessage.success("添加成功");
        } else {
          await updateCustomer(form);
          ElMessage.success("更新成功");
        }
        dialogVisible.value = false;
        await loadCustomerList();
      } catch (error) {
        ElMessage.error(isAdd.value ? "添加失败" : "更新失败");
        console.error(error);
      }
    };

    // 删除客户
    const handleDelete = async (id) => {
      try {
        await deleteCustomer(id);
        ElMessage.success("删除成功");
        await loadCustomerList();
      } catch (error) {
        ElMessage.error("删除失败");
        console.error(error);
      }
    };

    // 改变客户状态(启用/停用)
    const handleStatusChange = async (row) => {
      try {
        if (row.status === 1) {
          await disableCustomer(row.customerId);
          ElMessage.success("停用成功");
        } else {
          await enableCustomer(row.customerId);
          ElMessage.success("启用成功");
        }
        await loadCustomerList();
      } catch (error) {
        ElMessage.error(row.status === 1 ? "停用失败" : "启用失败");
        console.error(error);
      }
    };

    // 页面加载时获取客户列表
    onMounted(() => {
      loadCustomerList();
    });

    return {
      customerList,
      keyword,
      loading,
      dialogVisible,
      dialogTitle,
      isAdd,
      form,
      rules,
      formRef,
      loadCustomerList,
      handleSearch,
      showAddDialog,
      handleEdit,
      submitForm,
      handleDelete,
      handleStatusChange,
    };
  },
};
</script>

<style scoped>
.customer-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>